<?php
namespace app\common\tool;
require_once '../extend/PHPExcel/PHPExcel.php';
class Excel
{
    protected $objPHPExcel;

    private static $instance = null;
 
    // 禁止被实例化
    private function __construct()
    {
        $this->objPHPExcel = new \PHPExcel();
    }
 
    // 禁止clone
    private function __clone()
    {
 
    }

    //  实例化自己并保存到$instance中，已实例化则直接调用
    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 导出消耗数据
     * @param array     $data
     * @param array     $fields
     */
    public function export_effect_data($data,$field,$title)
    {
        try {
            $cn_header = $field['cn_header'];
            $en_to_cn = $field['en_to_cn'];
            $coloumheader = $field['coloumheader'];
            $objPHPExcel = $this->objPHPExcel;
            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->getActiveSheet()->setTitle("$title");
            for( $i=0 ; $i <= count($cn_header)-1; $i++){
                $objPHPExcel->getActiveSheet()->setCellValue("$coloumheader[$i]".'1',"$cn_header[$i]");
            }
            foreach($data as $key => $value){
                foreach ($coloumheader as $k => $v) {
                    $writevalue = $value[$en_to_cn[$v]];
                    if(is_string_float($writevalue)){
                        $writevalue = round($writevalue,2);    
                    }
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue("{$v}".($key+2),$writevalue);            
                }    
            }
            ob_end_clean();
            header('pragma:public');
            header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$title.'.xlsx"');
            header('Content-Disposition: attachment;filename="'.$title.'.xlsx"');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}